import 'package:flutter_test/flutter_test.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:lmmi/common/index.dart';

void main() {
  group('Username Update Demo - Before and After Fix', () {
    setUpAll(() async {
      // 初始化Hive（内存模式用于测试）
      Hive.init('test');

      // 注册适配器
      if (!Hive.isAdapterRegistered(0)) {
        Hive.registerAdapter(UserEntityAdapter());
      }
      if (!Hive.isAdapterRegistered(1)) {
        Hive.registerAdapter(ShareEntityAdapter());
      }

      // 初始化服务
      await UserService.initialize();
    });

    tearDownAll(() async {
      await Hive.deleteFromDisk();
    });

    setUp(() async {
      // 清理测试数据
      final userBox = Hive.box<UserEntity>('users');
      final currentUserBox = Hive.box('current_user');
      await userBox.clear();
      await currentUserBox.clear();
    });

    test('Demo: Username update behavior with fix', () async {
      print('\n=== 用户名修改修复演示 ===');

      // 1. 创建初始用户
      final originalUser = UserEntity(
        id: 'demo_user_123',
        username: 'john_doe',
        password: 'password123',
        avatar: 'avatar.jpg',
        share: ['share1', 'share2'],
        isVip: true,
        like: ['like1', 'like2'],
      );

      print('\n1. 创建用户: ${originalUser.username}');
      await UserService.updateUser(originalUser);

      // 设置为当前用户
      final currentUserBox = Hive.box('current_user');
      await currentUserBox.put('user', originalUser.toJson());

      final box = Hive.box<UserEntity>('users');
      print('   数据库中的用户: ${box.keys.toList()}');
      print('   用户数量: ${box.length}');

      // 2. 修改用户名
      final updatedUser = originalUser.copyWith(username: 'john_smith');
      print('\n2. 修改用户名: ${originalUser.username} -> ${updatedUser.username}');

      await UserService.updateUser(updatedUser);

      print('   修改后数据库中的用户: ${box.keys.toList()}');
      print('   用户数量: ${box.length}');

      // 3. 验证修复效果
      print('\n3. 验证修复效果:');
      print(
        '   ✓ 旧用户名 "${originalUser.username}" 是否存在: ${box.containsKey(originalUser.username)}',
      );
      print(
        '   ✓ 新用户名 "${updatedUser.username}" 是否存在: ${box.containsKey(updatedUser.username)}',
      );

      final retrievedUser = box.get(updatedUser.username);
      print('   ✓ 用户数据完整性:');
      print('     - ID: ${retrievedUser?.id}');
      print('     - 用户名: ${retrievedUser?.username}');
      print('     - 分享: ${retrievedUser?.share}');
      print('     - VIP状态: ${retrievedUser?.isVip}');
      print('     - 点赞: ${retrievedUser?.like}');

      // 4. 验证当前用户信息也已更新
      final currentUser = UserService.getCurrentUser();
      print('\n4. 当前用户信息:');
      print('   ✓ 当前用户名: ${currentUser?.username}');
      print('   ✓ 当前用户ID: ${currentUser?.id}');

      // 断言验证
      expect(box.containsKey('john_doe'), isFalse, reason: '旧用户名记录应该被删除');
      expect(box.containsKey('john_smith'), isTrue, reason: '新用户名记录应该存在');
      expect(box.length, equals(1), reason: '数据库中应该只有一个用户记录');
      expect(retrievedUser?.id, equals('demo_user_123'), reason: '用户ID应该保持不变');
      expect(
        retrievedUser?.share,
        equals(['share1', 'share2']),
        reason: '用户数据应该完整保留',
      );
      expect(
        currentUser?.username,
        equals('john_smith'),
        reason: '当前用户信息应该同步更新',
      );

      print('\n=== 修复验证成功！===');
      print('✅ 旧用户记录已删除');
      print('✅ 新用户记录已创建');
      print('✅ 用户数据完整保留');
      print('✅ 当前用户信息同步更新');
      print('✅ 数据库中没有重复记录');
    });

    test('Demo: Multiple users username update', () async {
      print('\n=== 多用户场景演示 ===');

      // 创建多个用户
      final user1 = UserEntity(
        id: 'user_1',
        username: 'alice',
        password: 'pass1',
        avatar: 'alice.jpg',
        share: [],
        isVip: false,
        like: [],
      );

      final user2 = UserEntity(
        id: 'user_2',
        username: 'bob',
        password: 'pass2',
        avatar: 'bob.jpg',
        share: ['share_bob'],
        isVip: true,
        like: [],
      );

      final user3 = UserEntity(
        id: 'user_3',
        username: 'charlie',
        password: 'pass3',
        avatar: 'charlie.jpg',
        share: [],
        isVip: false,
        like: ['like1', 'like2'],
      );

      print('\n1. 创建多个用户:');
      await UserService.updateUser(user1);
      await UserService.updateUser(user2);
      await UserService.updateUser(user3);

      final box = Hive.box<UserEntity>('users');
      print('   初始用户: ${box.keys.toList()}');
      print('   用户数量: ${box.length}');

      // 设置user1为当前用户
      final currentUserBox = Hive.box('current_user');
      await currentUserBox.put('user', user1.toJson());

      // 修改user2的用户名（非当前用户）
      print('\n2. 修改非当前用户的用户名: bob -> robert');
      final updatedUser2 = user2.copyWith(username: 'robert');
      await UserService.updateUser(updatedUser2);

      print('   修改后用户: ${box.keys.toList()}');
      print('   用户数量: ${box.length}');

      // 修改当前用户的用户名
      print('\n3. 修改当前用户的用户名: alice -> alicia');
      final updatedUser1 = user1.copyWith(username: 'alicia');
      await UserService.updateUser(updatedUser1);

      print('   最终用户: ${box.keys.toList()}');
      print('   用户数量: ${box.length}');

      // 验证结果
      expect(box.containsKey('alice'), isFalse);
      expect(box.containsKey('bob'), isFalse);
      expect(box.containsKey('charlie'), isTrue);
      expect(box.containsKey('alicia'), isTrue);
      expect(box.containsKey('robert'), isTrue);
      expect(box.length, equals(3));

      // 验证当前用户信息
      final currentUser = UserService.getCurrentUser();
      expect(currentUser?.username, equals('alicia'));

      print('\n=== 多用户场景验证成功！===');
      print('✅ 所有用户名修改都正确处理');
      print('✅ 没有产生重复记录');
      print('✅ 当前用户信息正确更新');
    });
  });
}
